package org.amicofragile.test.springintegration.transformation;

import java.io.File;
import java.io.IOException;
import java.util.List;

import org.amicofragile.test.springintegration.dto.Person;
import org.apache.commons.io.FileUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.integration.annotation.Transformer;

public class FileToPersonTransformer
{
	private static final Log LOG = LogFactory.getLog(FileToPersonTransformer.class);

	@Transformer
	public Person parseFile(final File file)
	{
		LOG.debug("Reading file: " + file.getAbsolutePath());
		try
		{
			List<String> rows = (List<String>) FileUtils.readLines(file);
			if (rows.size() == 2)
			{
				final String nome = rows.get(0).substring(rows.get(0).indexOf(':') + 1).trim();
				final String cognome = rows.get(1).substring(rows.get(1).indexOf(':') + 1).trim();
				return new Person(nome, cognome);
			}
			LOG.warn("Unable to read person information from file " + file.getCanonicalPath());
		} catch (IOException e)
		{
			LOG.error("Error reading file " + file.getAbsolutePath(), e);
		}
		return null;
	}
}
